package com.xy.submit.configs;

import cn.hutool.core.util.RandomUtil;
import com.xy.cloud.service.RedisService;
import com.xy.submit.annotations.ExcludeMethodRepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 阻止拦截器Handler
 *
 * @author sunkl
 * @date 2020/3/18 14:32
 */


@Slf4j
public class PreventRepeatInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //log.info("========================执行拦截器了...==========================");
        //防止重复提交的满足条件： 1.启动类有ExcludeRepeatSubmit注解  2.方法上有ExcludeMethodRepeatSubmit注解  3.前段请求头含有sbKey
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            ExcludeMethodRepeatSubmit annotation = method.getAnnotation(ExcludeMethodRepeatSubmit.class);
            if (Objects.isNull(annotation)) {
                return true;
            } else {
              //  String sbKey = request.getHeader("sbKey");
                String sbKey = request.getParameter("sbKey");
                if(StringUtils.isEmpty(sbKey)){
                    return true;
                }
                long time = Long.parseLong(annotation.time());
                Boolean sb = redisService.setNx(sbKey, RandomUtil.randomNumbers(1),time);
                if (!sb) {
                    redisService.expire(sbKey,time, TimeUnit.MILLISECONDS);
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write("{\"code\":1002,\"message:\":\"重复请求\",\"data\":null}");
                    writer.flush();
                    writer.close();
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {

    }
}
